#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define HIST_SIZE 16384
#define MAXVAL 16383

int main(int argc, char *argv[])
{
  char *ifn, *ofn;
  FILE *in, *out;
  unsigned int col;
  unsigned int i;
  signed int line[4];
  unsigned int count;
  unsigned int start_x, start_y, end_x, end_y,last_y, last_x;
  unsigned int hist[HIST_SIZE];

  if(argc!=4) {
    printf("usage: %s [infile] [outfile] [column]\n\n",argv[0]);
    exit(1);
  }

  ifn=argv[1]; ofn=argv[2]; col=atoi(argv[3]);
  printf("input file: %s\noutput file: %s\ncolumn: %d\n\n",
	 ifn,ofn,col);

  if(col>3) {
    printf("error: column=%d - must be in range 0..3\n\n",col);
    exit(1);
  }

  if(!(in=fopen(ifn,"r"))) {
    printf("error: could not open %s\n\n",ifn); exit(1);
  }

  if(!(out=fopen(ofn,"w"))) {
    printf("error: could not open %s\n\n",ofn); exit(1);
  }

  printf("searching start point...\n");
  i=0; last_y=1000;

  count=0;
  while(!feof(in)) {
    fscanf(in,"%d %d %d %d",line,line+1,line+2,line+3);

    if(line[col]<MAXVAL) {
      if(count>2000) {
	start_x=i; start_y=line[col];
	printf("found start point: x=%d y=%d\n\n",start_x,start_y);
	i++; count=0; break;
      }
      else count=0;
    }
    else count++;

    i++;
  }

  printf("searching end point...\n");
  while(!feof(in)) {
    fscanf(in,"%d %d %d %d",line,line+1,line+2,line+3);

    if(count>2000) {
      end_x=last_x;
      end_y=last_y;
    }
    if(line[col]<MAXVAL) {
      count=0; last_x=i; last_y=line[col];
    }
    else count++;

    i++;
  }

  printf("found end point: x=%d y=%d\n\n",end_x,end_y);

  printf("rewinding file an calculating histogram...\n\n");

  //clear histogramm;
  for(i=0; i<HIST_SIZE; i++) hist[i]=0;

  fseek(in,0,SEEK_SET);
  for(i=0; i< start_x; i++)
    fscanf(in,"%d %d %d %d",line,line+1,line+2,line+3);

  for(; i < end_x + 1; i++ ) {
    fscanf(in,"%d %d %d %d",line,line+1,line+2,line+3);
    //printf("%d %d\n", i, line[col]);
    hist[ line[ col ] ] ++;

    if(feof(in)) {
      printf("error: unexpected end of file\n\n");
      break;
    }
  }

  //write out histogramm
  for(i=0; i<HIST_SIZE; i++) {
    fprintf(out,"%d %d\n",i,hist[i]);
  }

  fclose(in);
  fclose(out);

  return 0;
}
